using System.IO;

namespace 文件搜索
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            listBox1.Items.Clear();
            string path = textBox2.Text;
            TraverseDirectory(path);
        }



        // 递归遍历目录的方法  
        void TraverseDirectory(string directoryPath)
        {
            try
            {
                // 获取指定目录下的所有文件和目录  
                string[] directories = Directory.GetDirectories(directoryPath);
                string[] files = Directory.GetFiles(directoryPath);

                // 遍历并打印文件  
                foreach (string file in files)
                {
                    Boolean b = MatchExtName(file, textBox3.Text);
                    if (b)
                    {
                        listBox1.Items.Add(file);
                    }
                }

                // 递归遍历子目录  
                foreach (string dir in directories)
                {
                    TraverseDirectory(dir);
                }
            }
            catch (Exception ex)
            {
                // 处理可能出现的异常，例如权限问题  
                //Console.WriteLine($"Error accessing {directoryPath}. Reason: {ex.Message}");
            }
        }


        /// <summary>
        /// 比较文件扩展名是否相等
        /// </summary>
        /// <param name="file"></param>
        /// <param name="searchExt"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        private bool MatchExtName(string file, string searchExt)
        {
            try
            {
                string extName = Path.GetExtension(file).ToLower();
                if (extName.Equals(searchExt.ToLower()))
                {
                    return true;
                }
            }
            catch (Exception ex)
            {

                throw new Exception("比较文件名报错",ex);
            }
            return false;
        }

        /// <summary>
        /// 比较文件名是否相等
        /// </summary>
        /// <param name="file"></param>
        /// <param name="searchFile"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        private bool MatchFileName(string file, string searchFile)  
        {
            string fileName = Path.GetFileName(file);
            try
            {
                if (fileName.Equals(searchFile))
                {
                    return true;
                }

            }catch(Exception ex)
            {
                throw new Exception("比较文件并报错",ex);
            }
            return false;
            
        }
    }
}
